<template>
    <el-row align="middle" type="flex" style="height:100vh">
        <el-col :span="8" :offset="8">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>请登录</span>
                    <el-button style="float: right; padding: 3px 0" type="text">
                      <router-link to="/reg">去注册</router-link>
                    </el-button>
                </div>
                <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="账号" prop="username">
                        <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
    </el-row>
</template>

<script>
    import {userLogin} from '../api/user'
    export default {
    data() {
      var validateUsername = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入账号'));
        } else {
          callback();
        }
      };
      var validatePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (value.length < 3) {
          callback(new Error('密码长度不能小于3'));
        } else {
          callback();
        }
      };
      return {
        ruleForm: {
          username: '张三丰',
          password: '123',
        },
        target:'/', //记录用户登录前想访问的路径
        rules: {
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.ruleForm);
            // 方法1:
            // userLogin(this.ruleForm) //此处可以发起登录请求
            // 方法2：
            this.$store.dispatch('my/userLoginAct',{
              info:this.ruleForm,
              target:this.target
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    },
    created () {
      let {target} = this.$route.query
      this.target = target
    },
  }
</script>

<style lang="less" scoped>

</style>